/**
 * 
 */
package com.trungkent.smsbackup.util;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.android.AuthActivity;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.trungkent.smsbackup.R;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;

/**
 * @author TrungKent
 * 
 */
public class DropboxUtils {
	public static final int DROPBOX_COMPLETED = 1;
	
	private static DropboxUtils instance;
	private static Context mContext;

	// If you'd like to change the access type to the full Dropbox instead of
	// an app folder, change this value.
	final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
	
	public static DropboxUtils getInstance(Context context) {
		if (instance == null) {
			mContext = context;
			return new DropboxUtils();
		}
		return instance;
	}

	public void checkAppKeySetup() {
		// Check to make sure that we have a valid app key
		if (Constants.DROP_BOX_APP_KEY.startsWith("CHANGE")
				|| Constants.DROP_BOX_APP_SECRET.startsWith("CHANGE")) {
			Utilities.showToast(mContext, R.string.error_drop_box_no_key);
			return;
		}

		// Check if the app has set up its manifest properly.
		Intent testIntent = new Intent(Intent.ACTION_VIEW);
		String scheme = "db-" + Constants.DROP_BOX_APP_KEY;
		String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
		testIntent.setData(Uri.parse(uri));
		PackageManager pm = mContext.getPackageManager();
		if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
			Utilities.showToast(mContext,
					mContext.getString(R.string.error_drop_box_wrong_schema)
							+ scheme);
		}
	}

	public void logOut(DropboxAPI<AndroidAuthSession> api) {
		// Remove credentials from the session
		api.getSession().unlink();
		// Clear our stored keys
		clearKeys();
	}

	public AndroidAuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(Constants.DROP_BOX_APP_KEY, Constants.DROP_BOX_APP_SECRET);
		AndroidAuthSession session;

		String[] stored = getKeys();
		if (stored != null) {
			AccessTokenPair accessToken = new AccessTokenPair(stored[0],
					stored[1]);
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE,
					accessToken);
		} else {
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
		}

		return session;
	}

	/**
	 * Shows keeping the access keys returned from Trusted Authenticator in a
	 * local store, rather than storing user name & password, and
	 * re-authenticating each time (which is not to be done, ever).
	 * 
	 * @return Array of [access_key, access_secret], or null if none stored
	 */
	public String[] getKeys() {
		SharedPreferences prefs = mContext.getSharedPreferences(Constants.ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(Constants.ACCESS_KEY_NAME, null);
		String secret = prefs.getString(Constants.ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}

	/**
	 * Shows keeping the access keys returned from Trusted Authenticator in a
	 * local store, rather than storing user name & password, and
	 * re-authenticating each time (which is not to be done, ever).
	 */
	public void storeKeys(String key, String secret) {
		// Save the access key for later
		SharedPreferences prefs = mContext.getSharedPreferences(Constants.ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(Constants.ACCESS_KEY_NAME, key);
		edit.putString(Constants.ACCESS_SECRET_NAME, secret);
		edit.commit();
	}

	public void clearKeys() {
		SharedPreferences prefs = mContext.getSharedPreferences(Constants.ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.clear();
		edit.commit();
	}
	
	public static void storeUserName(String userName) {
		SharedPreferences prefs = mContext.getSharedPreferences(Constants.ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(Constants.DROP_BOX_USER_NAME, userName);
		edit.commit();
	}
	
	public static String getAccountName() {
		SharedPreferences prefs = mContext.getSharedPreferences(Constants.ACCOUNT_PREFS_NAME, 0);
		return prefs.getString(Constants.DROP_BOX_USER_NAME, null);
	}
}
